import { getCampusSelector } from '@/api/campus/campus'
import custom from '@/utils/custom'
import request from '@/utils/request'
import FlowBox from '@/views/workFlow/components/FlowBox'
import FollowUpDialog from './flowup/index.vue'

export default {
  components: { FlowBox, FollowUpDialog },

  filters: {
    dateFormat(value) {
      if (!value) return ''
      return custom.dateFormat(value, 'YYYY-MM-DD HH:mm')
    }
  },

  data() {
    return {
      showAll: false,
      query: {
        campusId: undefined,
        openDate: undefined,
        counselor: undefined,
        reach: undefined,
        company: undefined,
        expectedFollowUpDate: undefined,
        flowState: undefined
      },
      list: [],
      listLoading: true,
      multipleSelection: [],
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'createTime'
      },
      formVisible: false,
      exportBoxVisible: false,
      flowVisible: false,
      followUpVisible: false,
      editFollowUpData: null,
      columnList: [{ prop: 'campusId', label: '辅导校区' }, { prop: 'openDate', label: '开业日期' }, { prop: 'counselor', label: '辅导师' }, { prop: 'startDate', label: '辅导开始日期' }, { prop: 'endDate', label: '辅导结束日期' }, { prop: 'degreeCount', label: '校区学位' }, { prop: 'regular', label: '正价招生数' }, { prop: 'lead', label: '引流招生数' }, { prop: 'summarize', label: '开业总结' }, { prop: 'expectedFollowUpDate', label: '预计回访时间' }],
      campusOptions: [],
      campusLoading: false,
      companyOptions: [{ enCode: '总部区域', label: '总部区域' }, { enCode: '河北分公司', label: '河北分公司' }, { enCode: '山东分公司', label: '山东分公司' }, { enCode: '西安分公司', label: '西安分公司' }],
      typeOptions: [{ fullName: '新校开业', id: '1' }, { fullName: '多校自主开业', id: '2' }],
      currentRow: null
    }
  },

  created() {
    this.initData()
    this.loadCampusOptions()
  },

  methods: {
    async loadCampusOptions() {
      try {
        this.campusLoading = true
        const params = { fields: 'id,fullName' }
        const res = await getCampusSelector(params)
        this.campusOptions = Array.isArray(res.data) ? res.data : []
      } catch (err) {
        console.error('加载校区下拉选项失败:', err)
        this.campusOptions = []
        this.$message && this.$message.error('校区选项加载失败')
      } finally {
        this.campusLoading = false
      }
    },

    // 初始化数据
    initData() {
      this.listLoading = true
      let _query = {
        ...this.listQuery,
        ...this.query
      }
      let query = {}
      for (let key in _query) {
        if (Array.isArray(_query[key])) {
          query[key] = _query[key].join()
        } else {
          query[key] = _query[key]
        }
      }
      request({
        url: `/api/campus/open`,
        method: 'GET',
        data: query
      }).then(res => {
        this.list = res.data.list.map(item => {
          if (item.followUp) {
            if (item.followUp.followUpDate) {
              item.followUp.followUpDate = custom.dateFormat(item.followUp.followUpDate, 'YYYY-MM-DD')
            }
            if (item.followUp.problemsSolved && item.followUp.problemsSolved.length > 50) {
              item.followUp.problemsSolved = item.followUp.problemsSolved.substring(0, 50) + '...'
            }
          }
          return item
        })
        this.total = res.data.pagination.total
        this.listLoading = false
      })
    },

    // 删除处理
    handleDel(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          request({
            url: `/api/campus/open/${id}`,
            method: 'DELETE'
          }).then(res => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData()
              }
            })
          })
        })
        .catch(() => {})
    },

    addOrUpdateHandle(id, flowState) {
      let data = {
        id: id || '',
        enCode: '#visualDevOpen',
        flowId: '483449916379628805',
        formType: 1,
        opType: flowState ? 0 : '-1',
        status: flowState
      }
      this.flowVisible = true
      this.$nextTick(() => {
        this.$refs.FlowBox.init(data)
      })
    },

    // 搜索
    search() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'openDate'
      }
      this.initData()
    },

    // 刷新
    refresh(isrRefresh) {
      this.formVisible = false
      if (isrRefresh) this.reset()
    },

    // 重置
    reset() {
      this.query = {
        campusId: undefined,
        openDate: undefined,
        counselor: undefined,
        reach: undefined,
        company: undefined,
        expectedFollowUpDate: undefined,
        flowState: undefined
      }
      this.search()
    },

    // 关闭流程
    colseFlow(isrRefresh) {
      this.flowVisible = false
      if (isrRefresh) this.reset()
    },

    // 判断是否可以添加回访
    canFollowUp(row) {
      return !!row.openDate && row.flowState === 2
    },

    // 处理添加回访
    handleFollowUp(row) {
      this.currentRow = row
      this.isFollowUpDetail = false
      this.followUpVisible = true
      this.$nextTick(() => {
        this.$refs.followUpDialog.showFollowUpDialog(row)
      })
    },
    handleEditFollowUp(row) {
      this.currentRow = row
      // 设置编辑模式数据（供子组件 isEditMode 使用）
      this.editFollowUpData = row.followUp || null
      this.isFollowUpDetail = false
      this.followUpVisible = true
      this.$nextTick(() => {
        if (this.$refs.followUpDialog) {
          // 优先填充编辑数据，确保界面立即呈现已有内容
          this.$refs.followUpDialog.fillEditData && this.$refs.followUpDialog.fillEditData()
          // 之后拉取最新详情以覆盖或补全
          this.$refs.followUpDialog.loadFollowUpDetail(row.id)
        }
      })
    },
    // 关闭回访对话框
    closeFollowUp(isrRefresh) {
      this.followUpVisible = false
      this.isFollowUpDetail = false
      if (isrRefresh) this.reset()
    },
    // 查看回访详情
    viewFollowUpDetail(row) {
      if (!row.followUp) {
        this.$message.warning('该记录暂无回访信息')
        return
      }
      this.currentRow = row
      this.isFollowUpDetail = true
      this.followUpVisible = true
      this.$nextTick(() => {
        // 以只读详情模式加载数据
        if (this.$refs.followUpDialog) {
          this.$refs.followUpDialog.loadFollowUpDetail(row.id)
        }
      })
    },
    // 关闭详情页面（旧逻辑保留）
    closeDetail() {
      this.detailVisible = false
      this.detailData = null
    }
  }
}
